// utils/http.js
let isRedirecting = false;
const request = (options) => {
  const token = wx.getStorageSync('token');

  // 允许跳过鉴权的请求
  if (!token && !options.noAuth) {
    if (!isRedirecting) {
      isRedirecting = true;
      wx.showModal({
        title: '未登录',
        content: '请先登录后再使用该功能',
        confirmText: '去登录',
        cancelText: '取消',
        success(res) {
          isRedirecting = false;
          if (res.confirm) {
            wx.navigateTo({
              url: '/subpackage/user/logn/logn'
            });
          }
        }
      });
    }
    return Promise.reject('未登录，已阻止请求');
  }

  return new Promise((resolve, reject) => {
    wx.request({
      ...options,
      header: {
        ...options.header,
        Authorization: token,
        token: token
      },
      success(res) {
        if (res.statusCode === 200) {
          // 后台返回的 code 也可能表示 token 失效
          if (res.data.code === 401) {
            wx.removeStorageSync('token');
            wx.showModal({
              title: '登录过期',
              content: '请重新登录',
              showCancel: false,
              success() {
                wx.navigateTo({ url: '/subpackage/user/logn/logn' });
              }
            });
            reject('登录过期');
          } else {
            resolve(res.data);
          }
        } else {
          wx.showToast({ title: '请求失败', icon: 'none' });
          reject(res);
        }
      },
      fail(err) {
        wx.showToast({ title: '网络错误', icon: 'none' });
        reject(err);
      }
    });
  });
};

// 快捷方法
const get = (url, data = {}, options = {}) =>
  request({ ...options, url, data, method: 'GET' });

const post = (url, data = {}, options = {}) =>
  request({ ...options, url, data, method: 'POST' });

module.exports = {
  request,
  get,
  post
};